<?php
require_once('config.php');
require_once('mysqlii.php');
require_once('downlink.php');

$db = MySqlii::getInstance();

$channelid = isset($_GET['channelid']) ? $_GET['channelid'] : '';

if(empty($channelid)) {
    exit();
}
$data = array();

$url = @$downLink[$channelid];

if (!empty($url)) {
	@write_log($channelid);
	//header("Location: $url"); 
	exit();
}

function write_log($channelid) {
	$name = basename($_SERVER['SCRIPT_FILENAME'], '.php');
	$ip = getIP();
	$data = array(
		'date' => date('Y-m-d'),
		'hours' => date('H:i:s'),
		'script_name' => $name,
		'get_data' => json_encode($_GET),
		'channel_id' => $channelid,
		'ip' =>$ip,
		'user_agent' => $_SERVER['HTTP_USER_AGENT'],
		//'create_time' => time();
	);
	create('down_log', $data);
}

function getIP() { 
    if (getenv('HTTP_CLIENT_IP')) { 
        $ip = getenv('HTTP_CLIENT_IP'); 
    } elseif (getenv('HTTP_X_FORWARDED_FOR')) { 
        $ip = getenv('HTTP_X_FORWARDED_FOR'); 
    } elseif (getenv('HTTP_X_FORWARDED')) { 
        $ip = getenv('HTTP_X_FORWARDED'); 
    } elseif (getenv('HTTP_FORWARDED_FOR')) { 
        $ip = getenv('HTTP_FORWARDED_FOR'); 
    } elseif (getenv('HTTP_FORWARDED')) { 
        $ip = getenv('HTTP_FORWARDED'); 
    } else { 
        $ip = $_SERVER['REMOTE_ADDR']; 
    } 
    return $ip; 
}


function create($tableName, $data)
{
	GLOBAL $db;
	$data['create_time'] = time();
	$newTableName = $tableName . date('Ym');
	$sql = "CREATE TABLE IF NOT EXISTS $newTableName LIKE $tableName";

	$db->query($sql);
	return $db->inserts($newTableName, $data);
}

?>
